Laravel DBのtimestampを使うときにハマったこと
$table->timestamps()で自動でcreated_atとupdated_atをつくってくれるのだが
型がtimestamp
デフォルト値が指定できない・アップデート時に更新したい
DBごとに事情が違う
MySQLのアップデート時の更新on update CURRENT_TIMESTAMPのようなシンタックスシュガーはPostgreSQLには存在しないので、トリガーを書く必要がある
書き方の例:LaravelのDB migrationで日付のデフォルトを指定 - Qiita
DB::raw()で指定するか、最近のLaravelならuseCurrentを指定する
指定した場合の各RDBMSでの挙動
https://github.com/laravel/framework/blob/580f816cb42183bcdb70750779bbb521ed5ff7dd/src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php#L687
PostgreSQLとMySQLで勝手が違う
DB::rawでデフォルト値を入れる
2013年時点のTaylor Otwellの考え
【Proposal】 Default value for Timestamp columns · Issue #369 · laravel/framework
PostgreSQLとMySQLではCURRENT_TIMESTAMP()の形式が違う
PostgreSQL: Documentation: 11: 9.9. Date/Time Functions and Operators
time with time zoneで返る
形式:YYYY-MM-DD HH:MM:SS.pppppp-tz
pはprecision
tzはUTCからの時差
Understanding PostgreSQL Timestamp Data Types
When adding an interval value to (or subtracting an interval value from) a timestamp with time zone value, the days component advances (or decrements) the date of the timestamp with time zone by the indicated number of days. Across daylight saving time changes (with the session time zone set to a time zone that recognizes DST), this means interval '1 day' does not necessarily equal interval '24 hours'. For example, with the session time zone set to CST7CDT, timestamp with time zone '2005-04-02 12:00-07' + interval '1 day' will produce timestamp with time zone '2005-04-03 12:00-06', while adding interval '24 hours' to the same initial timestamp with time zone produces timestamp with time zone '2005-04-03 13:00-06', as there is a change in daylight saving time at 2005-04-03 02:00 in time zone CST7CDT.
https://www.postgresql.org/docs/9.1/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT
例:2001-12-23 14:39:53.662522-05
PostgreSQLでのtimestampとtime zone | en30's blog
MySQL :: MySQL 8.0 Reference Manual :: 12.7 Date and Time Functions
stringとして扱う場合YYYY-MM-DD HH:MM:SS形式で返る
例:2007-12-15 23:50:26
備考:NOW()のシノニム(postgreSQLでもそう)
MySQLの場合
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
あるいは$table->timestamp('created_at')->useCurrent();としたらよい
PostgreSQLの場合
$table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)'))
タイムゾーンありだとtimestamp()には末尾にタイムゾーン情報がつくのでトラブりそう?kadoyau.icon
php - How can I set the default value of a timestamp column to the current timestamp with Laravel migrations? - Stack Overflow
#Laravel_5